<template>
	<div class="app-container">
		<el-tabs v-model="activeName" type="card" @tab-click="handleClick">
			<el-tab-pane label="我的合同" name="0"></el-tab-pane>
			<el-tab-pane label="全部合同" name="5" v-if="hasRole(['admin', 'BOSS', 'DEPT_LEADER'])"></el-tab-pane>
		</el-tabs>

		<!-- 查询 -->
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" class="searchBox">

			<el-form-item label="签约公司" prop="businessCode">
				<el-input v-model="queryParams.businessCode" placeholder="请输入关键字" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>

			<el-form-item label="合同类型" prop="type">
				<el-select v-model="queryParams.type" filterable placeholder="请选择类型">
					<el-option v-for="item in contractType" :key="item.label"
						:label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="盖章类型" prop="signType">
				<el-select v-model="queryParams.signType" filterable placeholder="请选择类型">
					<el-option v-for="item in stampType" :key="item.label"
						:label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="状态" prop="status">
				<el-select v-model="queryParams.status" filterable placeholder="请选择类型">
					<el-option v-for="item in contractStatus" :key="item.label"
						:label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="用户名称" prop="uid">
				<el-select v-model="queryParams.uid" filterable placeholder="请选择用户">
					<el-option v-for="item in userData" :key="item.userId" :label="item.nickName" :value="item.userId">
					</el-option>
				</el-select>
			</el-form-item>

			<!-- <el-form-item label="部门" prop="deptId" v-if="activeName == 5">
				<treeselect style="width: 215px;" v-model="queryParams.deptId" :options="deptOptions" :show-count="true"
					placeholder="请选择部门" />
			</el-form-item> -->

			<el-form-item label="时间" prop="timeData" style="width: 324px;">
				<el-date-picker v-model="timeData" type="daterange" range-separator="至" start-placeholder="开始日期"
					end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="timeChange">
				</el-date-picker>
			</el-form-item>

			<el-form-item class="searchBtnLine">
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<!-- 按钮 -->
		<el-row :gutter="10" class="mb8" v-if="activeName == 0">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['business:bxExpense:add']">新增
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
					@click="handleDelete" v-hasPermi="['business:bxExpense:remove']">删除
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-download" size="mini" :disabled="multiple"
					@click="handleDownload" >下载附件
				</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<!-- 报销管理表格 -->
		<el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
			<!-- 选择列 -->
			<el-table-column type="selection" width="55" align="center" />
			<!-- 其他列 -->
			<!-- <el-table-column label="合同编号" align="left" prop="businessCode"  width="280"  /> -->
			<el-table-column label="合同类型" align="center" prop="type"  width="100">
				<template slot-scope="scope">
					<span v-if="scope.row.type === 1">采购合同</span>
					<span v-if="scope.row.type === 2">销售合同</span>
				</template>
			</el-table-column>
			<el-table-column label="签约公司" align="center" prop="signCompany"  width="280"/>
			<el-table-column label="盖章情况" align="center" prop="signType" width="100"  >
				<template slot-scope="scope">
					<span v-if="scope.row.signType === 1">单章</span>
					<span v-if="scope.row.signType === 2">双章</span>
				</template>
			</el-table-column>
			<el-table-column label="合同金额" align="center" prop="contractPrice" >
				<template slot-scope="scope">
					<span>{{ towNumber(scope.row.contractPrice) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="收/付款合计金额" align="center" prop="totalPrice" >
				<template slot-scope="scope">
					<span>{{ towNumber(scope.row.totalPrice) }}</span>
				</template>
			</el-table-column>
			<!-- <el-table-column label="签约人员" align="center" prop="personnel" /> -->

			<el-table-column  label="状态" align="center" prop="status" >
				<template slot-scope="scope">
					<el-tag type="danger"  v-if="scope.row.status==0">未结清</el-tag>
					<el-tag type="success" v-if="scope.row.status==9">已结清</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="附件数量" align="center" prop="dtlCnt"  width="80"/>	



			<el-table-column sortable label="签约时间" align="center" prop="businessDate" >
				<!-- 时间格式化 -->
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.businessDate, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>

			<el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
				<!-- 操作按钮 -->
				<template slot-scope="scope">
					<!-- <el-button size="mini" type="text" icon="el-icon-document-copy" @click="handleReceipt(scope.row)">
						发票
					</el-button> -->
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)"
						v-hasPermi="['business:bxExpense:edit']" v-if="activeName == 0">
						修改
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">
						查看
					</el-button>

					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
						v-hasPermi="['business:bxExpense:remove']" v-if=" activeName == 0">
						删除
					</el-button>
				</template>

			</el-table-column>
		</el-table>

		<!-- 分页组件 -->
		<pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList" />

		<detailForm ref="detailForm" :title="title" v-if="formVisble" @close="handleClose"></detailForm>

		<!-- <ticketsForm ref="ticketsForm" :title="title" v-if="ticketsFormVisble" @close2="handleClose2"></ticketsForm> -->

		<el-dialog title="单据打印预览" custom-class="printPreview" :visible.sync="printShow" width="297mm" append-to-body>
			<bxTemplate :rowData="rowData"></bxTemplate>
		</el-dialog>
	</div>
</template>

<script>
import { saveAs } from 'file-saver'
import JSZip from 'jszip';
	import {
		listBxContract,
		getBxContract,
		delBxContract,
		updateBxExpense,
		downloadContractFiles
	} from "@/api/contract/contractMain";

	import {
		listUser
	} from "@/api/system/user"

	import {
		deptTreeSelect
	} from "@/api/system/user";

	import Treeselect from "@riophae/vue-treeselect";
	import "@riophae/vue-treeselect/dist/vue-treeselect.css";

	import detailForm from "./detailForm.vue";
	// import ticketsForm from './ticketsForm.vue'

	import bxTemplate from "../bxTemplate/index.vue"

	export default {
		components: {
			Treeselect,
			detailForm,
			bxTemplate,
			// ticketsForm
		},
		data() {
			return {
				// 当前激活的选项卡
				activeName: "0",
				// 是否显示加载遮罩层
				loading: true,
				// 选中的数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 是否显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				//合同数据，
				contractList:[],
				// 报销管理表格数据
				bxExpenseList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 用户数据
				userData: [],  
				
				contractType:[
					{label:'采购合同',value:1},
					{label:'销售合同',value:2},
				],
				stampType:[
					{label:'单章',value:1},
					{label:'双章',value:2},
				],
				contractStatus:[
					{label:'未结清',value:0},
					{label:'已结清',value:9},
				],
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					// 默认Type为"1"常规报销
					type: null,
					uid: null,
					status: null,
					statuses: null,
					deptId: null,
					startTime: null,
					endTime: null,
				},
				// 用户角色
				roles: [],
				// 查询条件时间
				timeData: [],
				// 新增修改弹窗
				formVisble: false,
				// 打印预览弹窗
				printShow: false,
				// 要打印的数据
				rowData: [],
				ticketsFormVisble:false,				
				upload: {
					// 回显
					baseUrl: process.env.VUE_APP_BASE_API,
				},
			};
		},
		watch: {
			$route: {
				handler: function(val, oldVal) {
					if (val.query.formParam == undefined) {
						this.formVisble = false;
					} else if (val.query.formParam == 'dHJ1ZQ==') {
						this.handleAdd();
					}
				},
				deep: true,
				immediate: true
			}
		},
		created() {
			this.getUserData();
			this.getDeptTree();
			// 从vuex(状态)中获取当前用户有哪些角色
			this.roles = this.$store.getters.roles;
			// 如果选项卡为"我的数据--0"时赋值查询UID(本人)
			if (this.activeName == 0) {
				this.queryParams.uid = this.$store.state.user.userId;
			};
			this.getList();
		},
		computed: {
			// 根据角色动态生成允许显示的选项卡
			allowedTabs() {
				const tabs = [{
						label: '我的数据',
						name: '0'
					},
					{
						label: '全部数据',
						name: '5',
						roles: ['admin', 'BOSS', 'DEPT_LEADER']
					}
				];
				return tabs.filter(tab => !tab.roles || this.hasRole(tab.roles));
			},
		},
		methods: {
			/** 查询 */
			getList() {
				this.loading = true;
				listBxContract(this.queryParams).then(response => {
					this.contractList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			// 获取用户列表
			getUserData() {
				listUser().then(res => {
					this.userData = res.rows;
				})
			},
			/** 查询部门下拉树结构 */
			getDeptTree() {
				deptTreeSelect().then(response => {
					this.deptOptions = response.data;
				});
			},
			// 查询条件时间选择
			timeChange(val) {
				this.queryParams.startTime = val[0] + " 00:00:00";
				this.queryParams.endTime = val[1] + " 23:59:59";
			},
			// 处理标签页点击事件
			handleClick(data) {
				this.activeName = data.name;
				if (data.name == 0) {
					this.queryParams.uid = this.$store.state.user.userId;
					this.queryParams.status = null;
					this.queryParams.statuses = null
				} else if (data.name == 5) {
					this.queryParams.uid = null;
					this.queryParams.status = null;
					this.queryParams.statuses = null;
				} else {
					this.queryParams.uid = null;
					this.queryParams.status = null;
					if (this.hasRole(['admin', 'BOSS'])) {
						this.queryParams.statuses = '1,2';
					} else if (this.hasRole(['DEPT_LEADER'])) {
						this.queryParams.statuses = '1';
					}
				}
				this.queryParams.pageNum = 1;
				this.queryParams.pageSize = 10;
				this.getList();
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.timeData = [];
				this.queryParams.startTime = null;
				this.queryParams.endTime = null;
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			
			// 新增合同
			handleAdd() {
				this.formVisble = true;
				this.title = "新增合同";
				setTimeout(() => {
					this.$refs.detailForm.initPage({
						isAdd: 'add',
						//type: 1
					})
				}, 50)
			},


			//查看发票
			handleReceipt(row){
				const id = row.id || this.ids
				this.ticketsFormVisble = true;
				this.title = "查看发票";
				setTimeout(() => {
					this.$refs.ticketsForm.initPage({
						id:id
					})					
				}, 50)
			},
			// 编辑
			handleEdit(row) {
				const id = row.id || this.ids
				getBxContract(id).then(res => {
					this.formVisble = true;
					this.title = "修改合同信息";
					setTimeout(() => {
						this.$refs.detailForm.initPage(res.data)
					}, 50)
				});
			},
			// 查看合同
			handleView(row) { 
				const id = row.id || this.ids
				this.formVisble = true;
				this.title = "查看合同信息";
				setTimeout(() => {
					this.$refs.detailForm.initPage({
						id:id,
						isAdd: 'check',
						nickName:row.nickName
					})
				}, 50)

			},
			/**关闭页面 */
			handleClose() {
				this.formVisble = false;
				this.getList();
			},
			/**关闭页面 */
			handleClose2() {
				this.ticketsFormVisble = false;
				this.getList();
			},
			// 检查是否具有审批权限
			checkApprovalPermission(roles) {
				let isAllow = true;
				if (this.activeName == 0) {
					isAllow = false;
				} else {
					const requiredRoles = ['admin', 'BOSS', 'DEPT_LEADER'];
					isAllow = requiredRoles.some(role => roles.indexOf(role) !== -1)
				}
				return isAllow;
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const ids = row.id || this.ids;
				this.$modal.confirm('是否确认删除"' + ids + '"的数据项？').then(function() {
					return delBxContract(ids);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			handleWithdraw(row) {
				row.status = 0;
				updateBxExpense(row).then(response => {
					this.$modal.msgSuccess("撤回成功");
					this.getList();
				})
			},
			handlePrint(row) {
				getBxContract(row.id).then(res => {
					this.printShow = true;
					this.rowData = res.data;
				})
			},
			//下载文件
			handleDownload(row){		
				const ids = row.id || this.ids;
			
				downloadContractFiles(ids).then(res => {
					
					if(res.data){
						//获取时间
						let yy = new Date().getFullYear();
						let mm = new Date().getMonth()+1;
						let dd = new Date().getDate();

						let allData=res.data

						//压缩转二进制流函数
						const zip = new JSZip();
						const blogTitle = yy+'-'+mm+'-'+dd+'.zip'
						const cache = {};
						const promises = [];
						//
						allData.forEach(item=>{
							if(item.file){
								var url = this.upload.baseUrl  + item.file
								const promise = this.getFile(url).then(data=>{
									// *下载文件, 并存成ArrayBuffer对象
									const fileName = item.fileName
									zip.file(fileName, data, { binary: true })
									cache[fileName] = data;
								})
								promises.push(promise);	
							}
						})
						Promise.all(promises).then(()=>{
							zip.generateAsync({
								type: "blob", compression: 'DEFLATE', // *STORE: 默认不压缩; DEFLATE：需要压缩
								compressionOptions: {
									level: 9 // *压缩等级 1~9。1: 压缩速度最快，9: 最优压缩方式
								}
							}).then(content=>{
								saveAs(content, blogTitle); // *生成二进制流，利用file-saver保存文件，文件名自定义
							})
						})

					}else{
				 		this.$modal.msgWarning("所选数据内无附件");
					}
				});		
			},
			//接上条，获取文件下载
			getFile(url) {
				return new Promise((resolve, reject) => {
					//通过请求获取文件blob格式
					let xmlhttp = new XMLHttpRequest();
					xmlhttp.open("GET", url, true);
					xmlhttp.responseType = "blob";
					xmlhttp.onload = function () {
					if (xmlhttp.status == 200) {
						resolve(xmlhttp.response);
					} else {
						reject(xmlhttp.response);
					}
					};
					xmlhttp.send();
				});
			},





			//下载文件
			handleDownload000000(row){		//备份，未使用的方法		
				const id = row.id || this.ids;
				if(this.single==false){
					getBxContract(id).then(res => {
						//判断是否有文件
						if(res.data.recordList){
							//console.log('-----------------res.data.recordList',res.data.recordList)
							let files = res.data.recordList.map(item=>{
								return	item.fileList
							})
							//console.log('---------新组成',files )
							let flatArr =Object.values(files).flat(Infinity)
							//console.log('---------展开',flatArr )
							let fileUrl =flatArr.map(item=>{
								return	{
									url:item.file,
									fileName:item.fileName
								}
							})
							//console.log('---------url',fileUrl )
							//压缩转二进制流函数
							const zip = new JSZip();
							const blogTitle = '附件打包.zip'
							const cache = {};
							const promises = [];
							//
							fileUrl.forEach(item=>{
								if(item.url){
									var url = this.upload.baseUrl  + item.url
									const promise = this.getFile(url).then(data=>{
										// *下载文件, 并存成ArrayBuffer对象
										const fileName = item.fileName
										zip.file(fileName, data, { binary: true })
										cache[fileName] = data;
									})
									promises.push(promise);
								}
							})
							Promise.all(promises).then(()=>{
								zip.generateAsync({
									type: "blob", compression: 'DEFLATE', // *STORE: 默认不压缩; DEFLATE：需要压缩
									compressionOptions: {
										level: 9 // *压缩等级 1~9。1: 压缩速度最快，9: 最优压缩方式
									}
								}).then(content=>{
									saveAs(content, blogTitle); // *生成二进制流，利用file-saver保存文件，文件名自定义
								})
							})
						}else{
							this.$modal.msgWarning("记录内无附件");
						}
					});
				}else{
					this.$modal.msgWarning("只能选择一条数据");
				}
			},




			//小数点2位
			towNumber(val) {
				return val.toFixed(2)
			}
		},
	};
</script>

<style>
	/* 可以添加样式 */
	.searchBox{
	}
	.searchBox .el-form-item__content{
		width:128px
	}
	.searchBox .el-form-item__content .el-range-editor.el-input__inner{
		width:248px
	}
	.searchBtnLine .el-form-item__content{
		width:170px;
	}
</style>
